/* 
Copyright (C) 2010- Peter Bui and Aaron Dingler.
This software is distributed under the GNU General Public License.
See the file COPYING for details.
*/

#include "smq_common.h"
#include "smq_catalog.h"
#include "smq_util.h"

#include <debug.h>
#include <catalog_query.h>
#include <catalog_server.h>

#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <nvpair.h>

enum {
    MODE_TABLE,
    MODE_LONG
};

static int SMQ_Status_Stalled_Timeout = SMQ_CLIENT_DEFAULT_STALLED_TIMEOUT;
static int SMQ_Status_Mode = MODE_TABLE;

static struct nvpair_header headers[] = {
    { "smq_queue",	NVPAIR_MODE_STRING,  NVPAIR_ALIGN_LEFT,   15},
    { "name",		NVPAIR_MODE_STRING,  NVPAIR_ALIGN_LEFT,   25},
    { "smq_port",	NVPAIR_MODE_INTEGER, NVPAIR_ALIGN_RIGHT,   8},
    { "version",	NVPAIR_MODE_STRING,  NVPAIR_ALIGN_RIGHT,   8},
    { "smq_messages",   NVPAIR_MODE_STRING,  NVPAIR_ALIGN_RIGHT,   8},
    { NULL, }
};

static void
smq_status_show_help(const char *progname)
{
    printf("usage: %s\n", progname);
    printf("Options:\n");
    printf(" -d <flag>   Enable debugging for this subsystem.\n");
    printf(" -t <time>   RPC timeout (default is %ds).\n", SMQ_Status_Stalled_Timeout);
    printf(" -l		 Long output.\n");
    printf(" -h          This message.\n");
}

static void
smq_status_parse_command_line_arguments(int argc, char *argv[])
{
    int	c;

    while ((c = getopt(argc, argv, "d:lt:h")) != -1) {
        switch (c) {
            case 'd': 
                debug_flags_set(optarg); 
                break;
            case 'l': 
                SMQ_Status_Mode = MODE_LONG;
                break;
            case 't': 
                SMQ_Status_Stalled_Timeout = atoi(optarg);
                break;
            case 'h':
                smq_status_show_help(argv[0]); 
                exit(EXIT_SUCCESS);
                break;
            default:
                smq_status_show_help(argv[0]); 
                exit(EXIT_FAILURE);
                break;
        }
    }
}

int
main(int argc, char *argv[])
{
    struct catalog_query *cq;
    struct nvpair *nv;
    
    smq_status_parse_command_line_arguments(argc, argv);

    if(optind > argc) {
        smq_status_show_help("smq_status");
        exit(EXIT_FAILURE);
    }
    
    cq = catalog_query_create(CATALOG_HOST, CATALOG_PORT, time(0) + SMQ_Status_Stalled_Timeout);

    if (SMQ_Status_Mode == MODE_TABLE) nvpair_print_table_header(stdout, headers);

    while ((nv = catalog_query_read(cq, time(0) + SMQ_Status_Stalled_Timeout))) {
        if (strcmp(nvpair_lookup_string(nv, "type"), "smq") == 0) {
	    if (SMQ_Status_Mode == MODE_TABLE)
		nvpair_print_table(nv, stdout, headers);
	    else
		nvpair_print_text(nv, stdout);
        }
        nvpair_delete(nv);
    }
    
    if (SMQ_Status_Mode == MODE_TABLE) nvpair_print_table_footer(stdout, headers);

    return EXIT_SUCCESS;
}


/* 
vim: sw=4 sts=4 ts=8 ft=cpp
*/
